const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    
  }, 

  // 跳转到地址列表
  toAddress: function (e) {
    // let id = e.currentTarget.id
    wx.navigateTo({
         url: '../address/address?cartIds=' + this.data.cartIds + '&cartType=' + this.data.cartType
    })
  },

  // 跳转到付费成功
  toSuccess: function (e) {
    // let id = e.currentTarget.id
   
    if (!this.data.defaultAddress){
          wx.showToast({
               title: '请填写地址',
               icon: 'none',
               duration: 1500
          })
          return
    }
       var addressId = this.data.defaultAddress.id
       var data = { 'memberId': app.globalData.userInfo.id, 'cartIds': this.data.cartIds ,'addressId':addressId}
       var promise = app.synPostData('order/create', data)
       promise.then(function (res) {
            if(res.data.code==0){
                 //开启预支付
                 wx.navigateTo({
                      url: '../payment/payment?orderIds=' + res.data.result.orderIds + '&payAmount=' + res.data.result.payAmount + '&cartType=' + res.data.result.cartType
                 })






            }else{
                 wx.showToast({
                      title: '创建订单失败',
                      icon: 'none',
                      duration: 1500
                 })
                 return
            }
       }); 
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
         cartIds:options.cartIds,
         cartType:options.cartType,
         addressId: options.addressId ? options.addressId:''
    })
   
       this.loadCarts()
       this.loadDefaultAddress()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },
  loadCarts:function(){
       let that = this
       var data = { 'memberId': app.globalData.userInfo.id,'cartIds':this.data.cartIds ,'cartType':this.data.cartType}
       var promise = app.synPostData('count/countCart', data)
       promise.then(function (res) {
            that.setData({
                 countDto: res.data.result
            })
       }); 
  },
  loadDefaultAddress:function(){
       let that = this
       var addressId=that.data.addressId
       if(addressId){
            var data = { 'addressId': addressId}
            var promise = app.synPostData('address/findOne', data)
            promise.then(function (res) {
                 that.setData({
                      defaultAddress: res.data.result
                 })
            });      
       }else{
            var data = { 'memberId': app.globalData.userInfo.id }
            var promise = app.synPostData('address/getDefault', data)
            promise.then(function (res) {
                 that.setData({
                      defaultAddress: res.data.result
                 })
            });
       }
  }
})